#include"head.h"
#define TLV_HEADER_SIZE 13
int send_all(int sockfd,const void *buf,size_t len){
    size_t total=0;
    const char*p=(const char*)buf;
    while(total<len){
        ssize_t n=send(sockfd,p+total,len-total,0);
        if(n<=0){
            if(n==0){
                printf("连接已关闭\n");
            }else{
                perror("发送数据失败");
            }
            return -1;
        }
        total+=n;
    }
    return 0;
}
//发送tlv
int sendTlv(int sockfd,TLV *tlv){
    char buf[TLV_HEADER_SIZE];
    buf[0]=tlv->type;
    memcpy(buf+1,&tlv->seq,4);
    memcpy(buf+5,&tlv->length,4);
    memcpy(buf+9,&tlv->username,9);
    memcpy(buf+18,&tlv->token,65);
    //发送头部
    if(send_all(sockfd,buf,sizeof(buf))!=0){
        return -1;
    }
    //发送数据部分
    if(tlv->length>0){
        return send_all(sockfd,tlv->value,tlv->length);
    }
    return 0;
}
int recv_all(int sockfd,void *buf,size_t len){
    size_t total=0;
    char *p=(char*)buf;
    while(total<len){
        ssize_t n=recv(sockfd,p+total,len-total,0);
        if(n<=0){
            if(n==0){
                printf("连接已关闭\n");
            }else{
                perror("接收数据失败");
            }
            return -1;
        }
        total+=n;
    }
    return 0;
}
//接收tlv
int recvTlv(int sockfd,TLV* tlv){
    char buf[TLV_HEADER_SIZE];
    recv_all(sockfd,buf,sizeof(buf));
    tlv->type=buf[0];
    memcpy(&tlv->seq,buf+1,4);
    memcpy(&tlv->length,buf+5,4);
    memcpy(&tlv->username,buf+9,9);
    tlv->username[8]='\0';
    memcpy(&tlv->token,buf+18,65);
    tlv->token[64]='\0';
    if(tlv->length>0){
        recv_all(sockfd,tlv->value,tlv->length);
    }
    return 0;
}
